82. 删除排序链表中的重复元素 II
为保证权益,题目请参考 82. 删除排序链表中的重复元素 II(From LeetCode).
解决方案1
CPP
C++
#include <set>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
set<int> waitToDelete;
// step 1
set<int> occurToFind;
ListNode* t = head;
while (t != nullptr) {
if (occurToFind.find(t->val) != occurToFind.end()) {
waitToDelete.insert(t->val);
} else {
occurToFind.insert(t->val);
}
t = t->next;
}
// step 2
ListNode* ans = head;
if (ans == nullptr) {
return nullptr;
}
while (ans != nullptr &&
waitToDelete.find(ans->val) != waitToDelete.end()) {
t = ans;
ans = ans->next;
delete t;
}
if (ans == nullptr) {
return nullptr;
}
ListNode* prior = ans;
while (prior->next != nullptr) {
if (waitToDelete.find(prior->next->val) != waitToDelete.end()) {
t = prior->next;
prior->next = prior->next->next;
delete t;
} else {
prior = prior->next;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61